package com.yungu.swift.api.base.handler;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.yungu.swift.api.base.Constants;
import com.yungu.swift.api.config.ApplicationConfig;
import com.yungu.swift.api.utils.RsaUtil;
import com.yungu.swift.assets.passenger.service.PassengerService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.SpringContextHolder;
import com.yungu.swift.constants.MagicConstant;
import com.yungu.swift.constants.PassengerConstant;
import com.yungu.swift.utils.JsonUtils;
import com.yungu.swift.utils.StringUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

import static com.yungu.swift.api.base.ApiErrorEnum.*;

/**
 * @author cuixiuyin
 * 乘客处理器 判断乘客登陆状态，以及将 token 转化为 uuid
 */
public class PassengerTokenHandler extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        String token = request.getHeader(Constants.TOKEN_KEY);
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(Constants.TOKEN_KEY);
        }
        if (StringUtils.isBlank(token) && request instanceof MultipartHttpServletRequest) {
            Part tokenPart = request.getPart(Constants.TOKEN_KEY);
            token = stream2Str(tokenPart.getInputStream());
        }
        if (StringUtils.isBlank(token)) {
            outPrint(out, JsonUtils.writeJsonStr(ResponseData.buildErrorResponse(NOT_LOGIN.getCode(), NOT_LOGIN.getMsg())));
            return false;
        }
        PassengerService passengerService = SpringContextHolder.getBean(PassengerService.class);
        Map<String, String> tokenResult = passengerService.getPassengerCachedByToken(token).getData();
        if (tokenResult == null) {
            ResponseData responseData = ResponseData.buildErrorResponse(LOGIN_EXPIRED.getCode(), LOGIN_EXPIRED.getMsg());
            outPrint(out, JsonUtils.writeJsonStr(responseData));
            return false;
        }
        if (StringUtils.isNull(tokenResult.get(MagicConstant.PARAMS_UUID))) {
            ResponseData responseData = ResponseData.buildErrorResponse(LOGIN_EXPIRED.getCode(), LOGIN_EXPIRED.getMsg());
            outPrint(out, JsonUtils.writeJsonStr(responseData));
            return false;
        }
        //封号拦截
        if (StringUtils.isNotNull(tokenResult.get("status"))) {
            int status = Integer.parseInt(tokenResult.get("status"));
            if (status != PassengerConstant.PASSENGER_STATUS_NORMAL) {
                ResponseData responseData = ResponseData.buildErrorResponse(USER_STATUS_ERROR.getCode(), USER_STATUS_ERROR.getMsg());
                outPrint(out, JsonUtils.writeJsonStr(responseData));
                return false;
            }
        }
        request.setAttribute("uuid", tokenResult.get("uuid"));
        response.reset();
        return true;
    }

    /**
     * 输出错误
     *
     * @param jsonstr
     */
    private void outPrint(PrintWriter out, String jsonstr) {
        if (ApplicationConfig.SERVER_CONFIG.getSafety().getEncrypt()) {
            out.print(RsaUtil.doUrlAndEncrypt(jsonstr));
        } else {
            out.print(jsonstr);
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

    }

    private String createJsonStr(String msg, int errCode, boolean result, Object data) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("msg", msg);
        map.put("errCode", errCode);
        map.put("success", result);
        map.put("data", data);
        try {
            return JsonUtils.writeJsonStr(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }

    private String stream2Str(InputStream inputStream) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String line;
            StringBuffer buffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            return buffer.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

}
